<?php
// $Id$

/**
 * Controller_Users 控制器
 */
class Controller_Users extends Controller_Abstract
{
	//积分获取赠送记录
	function actionunionlist()
	{
		$this->union_table = Logs::meta();
		$this->lists(array('userid'=>$_SESSION[helper_users_login::$_Login_SessionKey]['userid'],'type'=>102));
	}
	function actionIndex()
	{
		return $this->_redirect(url('users/home'));
	}
	//找回密码
	function actiongetpwd()
	{
		if ($this->_context->isPOST())
		{
			$result = array(
				'status'=>false,
				'message'=>'数据不完整',
				'result'=>-1
			);
			$userphone = isset($this->_context->userphone)?$this->_context->userphone:null;
			$newpass = isset($this->_context->newpass)?$this->_context->newpass:null;
			$sms_code = isset($this->_context->smscode)?$this->_context->smscode:null;
			$img_code = isset($this->_context->rndcode)?$this->_context->rndcode:null;
			if (!is_null($userphone) && !is_null($newpass) && !is_null($sms_code) && !is_null($img_code))
			{
				if (!Helper_Ckcode::check($img_code))
				{
					$result['message'] = '图片验证码不正确';
				}else if (!helper_sms_reg::validate($sms_code))
				{
					$result['message'] = '短信认证码不正确';
				}else if (!helper_userbase_reg::validate_mobile_reg($userphone)){
					$result['message'] = '不存在此用户';
				}else
				{
					$userbase = Userbase::find('userphone = ?',$userphone)->getOne();
					if ($userbase->id())
					{
						$status = helper_users_login::getpwd($userbase, $newpass);
						if ($status === true)
						{
							$result['status'] = true;
						}else
						{
							$result['message'] = '修改失败';
						}
					}else {
						$result['message'] = '用户数据错误';
					}
				}
			}
				
			exit(json_encode($result));
		}



		//$this->_view['flag'] = $SendFlag;
	}
	/**
	 *
	 *2012-1-2-下午01:55:00 by 460932465
	 * @return 赠送积分
	 */
	function actionsendpoint()
	{
		$userbase = helper_users_login::userbase();
		if($this->_context->isGET())
		{
			$this->_view['userdata'] = $userbase;
		}else {
			$target_phone = isset($this->_context->target_phone)?$this->_context->target_phone:null;
			$point = isset($this->_context->point)?$this->_context->point:null;
				
			$result = array(
				'status'=>false,
				'message'=>'数据不完整',
				'result'=>-1
			);
			if (!is_null($target_phone) &&  !is_null($point))
			{
				$point = floor($point);
				if ($point < 100)
				{
					$result['message'] = '对不起，赠送的积分必须大于100分';
				}else
				{
					$send = new helper_users_point($userbase);
					$status = $send->send($target_phone, $point);
					if ($status === true)
					{
						Logs::_log(helper_users_login::userbase()->userid, $this->_context->requestUDI(),"成功赠送给:{$target_phone} {$point}分");
						$result['status'] = true;
						$result['result'] = $userbase->userpoint;
					}else
					{
						$result['message'] = $send->errmsg;
					}
				}

			}
			exit(json_encode($result));
		}

	}
	function actionuserinfo()
	{
		$this->_view['userdata'] = helper_users_login::userbase();
	}
	function actioncardlist()
	{
		$this->page_size = 10;
		$userdata = helper_users_login::userbase();
		$this->_view['userdata'] = $userdata;
		$this->union_table = Orders::meta();
		$this->lists(array('userid'=>$userdata->userid));
	}
	function actionpointlist()
	{
		$this->page_size = 6;
		$userdata = helper_users_login::userbase();
		$this->_view['userdata'] = $userdata;
		$this->union_table = Orders::meta();
		$this->lists(array('type'=>1,'userid'=>$userdata->userid));
	}

	function actioncardpay()
	{
		$userbase = helper_users_login::userbase();
		if($this->_context->isGET())
		{
			$this->_view['userdata'] = $userbase;
		}else {
			$userphone = isset($this->_context->userphone)?trim($this->_context->userphone):null;
			$code =  isset($this->_context->code)?trim($this->_context->code):null;
			$pass =  isset($this->_context->pass)?trim($this->_context->pass):null;
			$result = array(
			'result'=>-1,
			'message'=>'数据不正确',
			'status'=>false
			);
			if (!is_null($userphone) && !is_null($code) && !is_null($pass))
			{
				$Userbase_Pay = Userbase::find('userphone = ?',$userphone)->getOne();
				if ($Userbase_Pay->id())
				{
					$cardpay = new helper_interface_pay($Userbase_Pay->userphone);
					$status = $cardpay->use_card($code,$pass);
					if ($status === true)
					{
						Logs::_log(helper_users_login::userbase()->userid, $this->_context->requestUDI(), "充值成功,卡号:{$code},密码:{$pass},充值绑定号:{$userphone}");
						$result['status'] = true;
						$result['result'] = helper_users_login::userbase()->usermoney; //获取最新余额
						$result['message'] = '充值成功';
					}else
					{
						$result['message'] = $cardpay->errmsg;
					}
				}else
				{
					$result['message'] = '充值的账号不存在';
				}
			}
				
			exit(json_encode($result));
				
				
				
		}
	}
	function actionchangepwd()
	{
		$userbase = helper_users_login::userbase();
		if($this->_context->isGET())
		{
			$this->_view['userdata'] = $userbase;
		}else {
			$result = array(
			'result'=>-1,
			'message'=>'数据不正确',
			'status'=>false
			);
			//$smscode = isset($this->_context->smscode)?trim($this->_context->smscode):null;
			$oldpass = isset($this->_context->oldpass)?trim($this->_context->oldpass):null;
			$newpass = isset($this->_context->newpass)?trim($this->_context->newpass):null;
			$configpass = isset($this->_context->configpass)?trim($this->_context->configpass):null;
				
			if( !is_null($oldpass) && !is_null($newpass) && !is_null($configpass))
			{
				if ($configpass != $newpass )
				{
					$result['message']  = '两次密码不一致';
				}else if(!Helper_Param::_number($newpass,1,10))
				{
					$result['message'] = '密码只能1-10位数字组成';
				}else
				{
					$status = helper_users_login::changepwd($oldpass, $newpass);
					if ($status === true )
					{
						$result['status'] = true;
					}else
					{
						$result['message'] = '密码修改失败';
					}
				}
			}
				
			exit(json_encode($result));
		}

	}

	/**
	 *
	 * 会员注册
	 */
	function actionreg()
	{
		$step = isset($this->_context->step)?intval($this->_context->step):0;
		//填写手机号码
		if ($step == 0)
		{
			$unlink = isset($this->_context->unlink)?intval($this->_context->unlink):'';
			$this->_view['unlink'] = $unlink;
			$this->_viewname = 'step0';
		}else if($step == 1)
		{//检测验证码 发送
			//POST
			$parentuserid = isset($this->_context->parentuserid)?($this->_context->parentuserid):0;
			$userphone = isset($this->_context->mobile)?($this->_context->mobile):0;
			//$mobile_rnd = isset($this->_context->mobile_rnd)?($this->_context->mobile_rnd):0;
			$img_code =  isset($this->_context->randvalue)?($this->_context->randvalue):0;
			 
			//验证图片
			if (Helper_Ckcode::check($img_code))
			{
				if(helper_userbase_reg::validate_mobile_reg($userphone))
				{
					$errstr = $userphone.' 已经被注册过了';
				}else
				{
						if($parentuserid != 0 && helper_userbase_reg::validate_userid_reg($parentuserid) == false)
						{
							$errstr = '推荐人不存在';
						}else {
							//开始注册
							$userInfo = array(
        						'userphone'=>$userphone,
        						'parentuserid'=>$parentuserid
							);
							$reg = new helper_userbase_reg();
							$status = $reg->reg($userInfo);
							 
							if ($status == true)
							{
								$userbase = $reg->userbase;
								//$errstr = '恭喜您注册成功,您的账号信息已经下发到您的手机';
								$errstr = '注册成功，您的账号:'.$reg->productcard->code.' 登陆密码:'.$reg->productcard->pass.',登陆地址：www.cr1000.net,感谢您使用DO CALL';
								//发送短信
								helper_sms_base::Post_Message($userbase->userphone, $errstr);
							}else
							{
								$errstr = $reg->errmsg;
							}
						}


				}
			}else
			{
				$errstr = '图片验证码错误';
			}
			 
			$this->_view['str'] = $errstr;
			$this->_viewname = 'step1';
		}else if ($step == 2 )
		{
			//注册提交，返回成功的账号和密码
		}
	}
	/**
	 *
	 * 会员登陆
	 */
	function actionlogin()
	{

		if($this->_context->isPOST())
		{
			$result = array('status'=>false,'message'=>'','url'=>url('default::users/home'));
			$userid = isset($this->_context->userid)?trim($this->_context->userid):null;
			$userpass = isset($this->_context->userpass)?trim($this->_context->userpass):null;
			$rndcode = isset($this->_context->rndcode)?trim($this->_context->rndcode):null;
			if(is_null($userid))
			{
				$result['message'] = '用户账号没有输入';
			}else if (is_null($userpass))
			{
				$result['message'] = '用户密码没有输入';
			}else if(is_null($rndcode))
			{
				$result['message'] = '验证码没有输入';
			}else if(!Helper_Ckcode::check($rndcode))
			{
				$result['message'] = '验证码错误';
			}else
			{
				$status = helper_users_login::_authLogin($userid, $userpass);
				if ($status == true)
				{
					$result['status'] = true;
					//记录日志
					Logs::_log(helper_users_login::userbase()->userid, $this->_context->requestUDI(), '登陆成功');
				}else
				{
					$result['message'] = '账号密码错误或者被锁定';
				}
			}
				
			exit(json_encode($result));
		}
	}
	/**
	 *
	 * 会员退出
	 */
	function actionLoginout()
	{
		//记录日志

		Logs::_log($_SESSION[helper_users_login::$_Login_SessionKey]['userid'], $this->_context->requestUDI(), '退出成功');
		helper_users_login::outlogin();
			
		return $this->_redirect(url('default'));
	}
	/**
	 *
	 * 会员中心首页
	 */
	function actionHome()
	{

		$this->_view['userdata'] = helper_users_login::userbase();
	}
	/**
	 *
	 * 会员中心推荐赚钱
	 */
	function actionRecommend()
	{
		$parentuserid = isset($this->_context->parentuserid)?trim($this->_context->parentuserid):$_SESSION[helper_users_login::$_Login_SessionKey]['userid'];
		$this->union_table = Userbase::meta();
		$this->lists(array('parentuserid'=>$parentuserid));

	}
	/**
	 *
	 * 会员中心充值购卡
	 */
	function actionPay()
	{
		$goodid = intval($this->_context->gid);
		if ($goodid)
		{
			$good_data = Product::find('id = ? and type = 0',$goodid)->getOne();
			if (!$good_data->id()) return $this->_redirect(url('users/pay'));
			// 提交数据
			$this->_view['good_data'] = $good_data;
			if ($this->_context->isPOST())
			{
				$username = trim($this->_context->post('username1'));
				$username1 = trim($this->_context->post('username2'));
				// 获取用户数据
				$user = Userbase::find('userid = ?',$username)->getOne();
				if ($user->id())
				{
					// 用户存在
					// 添加订单
					$orderid = Orders::get_orderid();
					$order_array = array(
						'orderid'=>$orderid,
						'ordertatolmoney'=>$good_data->price,
						'userid'=>$_SESSION[helper_users_login::$_Login_SessionKey]['userid'],
						'target_userid'=>$user->userid,
						'createtime'=>time(),
						'p_code'=>$good_data->p_code
					);
					// 生成支付信息
					$order = new Orders($order_array);
					$order->save();
					// 加载支付按钮信息
					$payment = new Helper_Payment_Bill();
					$payment->_order = array(
						'username'=>$order_array['userid'],
						'useremail'=>$user->email || '',
						'orderid'=>$order->orderid,
						'money'=>$order->ordertatolmoney / 100,
						'good_title'=>$good_data->title,
						'good_id'=>$good_data->p_code,
						'good_desc'=>'',
						'ext1'=>'',
						'ext2'=>''
					);
					$button = $payment->create_button();
					$this->_view['button'] = $button;
					$this->_view['order'] = $order;
				}else{
					return $this->_redirectMessage('出错啦!', '您输入的账户不存在!', url('users/pay',array('gid',$goodid)));
				}
				$this->_viewname = 'pay_step_confirm';
			}else{
				$this->_viewname = 'pay_step_post';
			}
		}else{
			$this->page_size = 6;
			$this->union_table = Product::meta();
			$this->lists(array('type'=>0,'isshow'=>1,'issell'=>1));
			// 加载产品分类
			$this->_view['good_category'] = Categorys::find('model = 2 and parentid = 78')->getAll();
		}
	}
	/**
	 *
	 * 会员中心积分兑换
	 */
	function actionPoint()
	{
		$goodid = intval($this->_context->gid);
		if ($goodid)
		{
			$good_data = Product::find('id = ? and type = 1',$goodid)->getOne();
			if (!$good_data->id()) return $this->_redirect(url('users/point'));
			// 提交数据
			if ($this->_context->isPOST())
			{
				// 参数校验
				$orderusername = trim($this->_context->post('orderusername'));// 用户姓名
				$orderaddress = trim($this->_context->post('orderaddress'));// 地址
				$ordertell = trim($this->_context->post('ordertell'));// 电话
				$orderzipcode = trim($this->_context->post('orderzipcode'));// 邮编
				if ($orderaddress == '' || $orderaddress=='' ||
				!Helper_Param::check($ordertell, 'call') ||
				$orderzipcode == '')
				{
					// 参数有误
					return $this->_redirectMessage('出错啦!', '参数填写不正确!', url('users/point',array('gid'=>$goodid)));
				}
				// 用户信息
				$user = helper_users_login::userbase();
				// 检测余额
				if ($user->userpoint < $good_data->pointer)
				{
					// 积分余额不足
					return $this->_redirectMessage('出错啦!', '您的积分余额不足,不能兑换!', url('users/point',array('gid'=>$goodid)));
				}
				// 订单入库
				$order_array = array(
					'orderid'=>Product::get_unique_code(),
					'type'=>1,
					'orderpointer'=>$good_data->pointer,
					'userid'=>$user->userid,
					'orderusername'=>$orderusername,
					'ordertell'=>$ordertell,
					'orderzipcode'=>$orderzipcode,
					'orderaddress'=>$orderaddress,
					'orderstatus'=>1,
					'createtime'=>time(),
					'p_code'=>$good_data->p_code,
				);
				$order_obj = new Orders($order_array);
				$order_obj->save();
				// 扣费
				$conn = QDB::getConn();
				$conn->startTrans();
				try {
					//扣费
					$conn->execute('update `voip_userbase` set `userpoint`=`userpoint`-'.$good_data->pointer.' where `userid`="'.$user->userid.'"');
					// 修改状态
					$order_obj->changeProps(array('orderstatus'=>2));
					$order_obj->save();
					$conn->completeTrans(true);
					Logs::_log($order_array['userid'], $this->_context->requestUDI(), '积分订单处理成功,订单编号:'.$order_obj->orderid);
						
					return $this->_redirectMessage('成功!', '您的订单处理成功!', url('users/home'));
				}catch (Exception $e){
					// 失败
					$conn->completeTrans(false);
					Logs::_log($order_array['userid'], $this->_context->requestUDI(), '积分订单处理失败:'.$order_array['orderid'].' / '.$e->getMessage());
					return $this->_redirectMessage('出错啦!', '您的订单处理失败!', url('users/point',array('gid'=>$goodid)));
				}
			}
			$this->_view['good_data'] = $good_data;
			$this->_viewname = 'point_step_post';
		}else{
			// 检测分类
			$this->page_size = 6;
			$this->union_table = Product::meta();
			$this->lists(array('type'=>1,'isshow'=>1,'issell'=>1));
			// 加载产品分类
			$this->_view['good_category'] = Categorys::find('model = 2 and parentid = 100')->getAll();
		}
	}
	function _before_execute()
	{
		$not_login = array(
			'login','reg','loginout','getpwd'
			);
			if ( !in_array($this->_context->action_name,$not_login) && !helper_users_login::is_login())
			{
				echo $this->_redirectMessage('出错啦!', '请您先登陆', url('users/login'))->execute();exit();
			}else {
				$this->_view['_UDI'] = $this->_context->requestUDI();
				$config = Configs::find()->order('id desc')->asArray()->getOne();
				if ($config && $config['isopen'] && $this->_context->ns != 'admin'){
					echo $config['closewhy'];exit;
				}
				$this->_view['config'] = $config;
				$cur_selected = $this->_context->action_name;
				$this->_view['selectd'] = $cur_selected;
			}
	}
}